package controllers;

import helpers.StringHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.UserModel;
import data.UserData;
import forms.UserForm;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	@SuppressWarnings("rawtypes")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		TreeMap check = new TreeMap();
		UserModel user = new UserModel();				
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/pages/login.jsp").forward(request,
					response);
		} catch (ServletException e) {

		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		HttpSession session = request.getSession();
		TreeMap check = new TreeMap();

		UserModel user = new UserModel();
		UserForm userForm = new UserForm();
		UserData userData = new UserData();

		TreeMap form = userForm.checkLogin(request, user);
		user = (UserModel) form.get("user");
		check = (TreeMap) form.get("checkValid");

		String returnUrl = (String) request.getParameter("returnUrl");

		if (check.size() == 0) {
			UserModel user_login = userData.getUser(user.getUsername());
			if (user_login != null) {
				if (user_login.getPassword().equalsIgnoreCase(
						StringHelper.md5(user.getPassword()))) {
					if (user_login.getStatus() == 2) {
						// Save login to session
						session.setAttribute("user_logged_in", user_login);
						if (returnUrl != null && returnUrl.length() > 0) {
							response.sendRedirect("/" + returnUrl);
							return;
						} else {
							response.sendRedirect("/");
							return;
						}

					} else {
						check.put("email",
								"Tài khoản bạn chưa được kích hoạt hoặc đang bị khóa.");
					}
				} else {
					check.put("password", "Mật khẩu không đúng");
				}
			} else {
				check.put("email", "Email truy cập không tồn tại.");
			}
		}

		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/pages/login.jsp").forward(request,
					response);
		} catch (ServletException e) {
			// e.printStackTrace();
		}
	}
}
